angular.module('App').controller('PatchUpdateController', ['$scope', '$http', 'BaseFunction', 'ParameterService','BaseSocket','BaseService','BaseModule','BaseEnum',
    function($scope, $http, BaseFunction, ParameterService,BaseSocket,BaseService,BaseModule,BaseEnum) {
        $scope.DeviceTypeEnum = BaseFunction.getEnum('AppEnum.DeviceType');
        $scope.Records;
        var serverUrl = "";
        $scope.patchNew = null;//云获得的最新补丁信息
        $scope.patchLocal = null;//本地补丁信息

        var publicSocket;
        BaseSocket.connect(function(skt){
            publicSocket = skt;
        });
    
        //初始化
        BaseModule.initModule($scope, 'App');
        // BaseFunction.request('/api/App/getSharedFileInfo', false, null, function(data){
        //     $scope.Records = data;
        // });
        BaseFunction.loading(true);
        ParameterService.getParameterValue(null, 'DownloadServer', function(dataUrl){
            serverUrl = dataUrl;
            //请求下载服务器传入数据
            var reqData = {
                EnterpriseID: '',    //企业ID
                Type: $scope.DeviceTypeEnum.SmartPlant.Value
            };

            BaseFunction.httpRequest(serverUrl + "/api/App/getApps", reqData, function(data){
                $scope.patchNew = data[0];
                $scope.Module.App.find({"Type" : 3},null,null,function(records){
                    $scope.patchLocal = records[0];
                    BaseFunction.loading(false);
                })
            });

        }); 

        $scope.zipTest = function(){
            ParameterService.getParameterValue(null,'CopyAddress', function(copyAddress){
                BaseFunction.loading(true);
                BaseService.filesZip(copyAddress, copyAddress+"/dist.zip", function(zipData){    
                    BaseFunction.loading(false);
                    console.log(zipData);
                    if(zipData==='close'){
                        console.log('close');
                    }
                },function(zipError){
                    console.log(zipError);
                    BaseFunction.loading(false);
                });
            }); 
        }
        //解压缩，删除，版本回退
        $scope.returnPatch = function(){
            BaseFunction.loading(true);
            ParameterService.getParameterValue(null,'CopyAddress', function(copyAddress){
                BaseService.filesUnzip(copyAddress+"/dist.zip", copyAddress, function(unzipData){    
                    if(unzipData==='close'){
                        console.log('close');
                        BaseService.deleteFiles([copyAddress+"/dist.zip"], function(count){ 
                            
                            $scope.Module.App.FocusedRecord.Version = $scope.Module.App.FocusedRecord.PreVersion;
                            $scope.Module.App.FocusedRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
                            $scope.Module.App.save(function(data){
                                BaseFunction.loading(false);
                            },function(err){
                                BaseFunction.loading(false);
                            });
                        },function(deleteError){
                            BaseFunction.loading(false);
                        });                   
                    }
                },function(unzipError){
                    console.log(unzipError);
                    BaseFunction.loading(false);
                });
            });
            
        }
        
        $scope.DownloadStatus = {
            No: 0,              //最新版本
            Downloadable: 1,    //可下载
            Updatable: 2,       //可更新
            Downloading: 3      //下载中
        };

        $scope.updatePatch= function(record, scheduleDiv, completeFun){
            //全部下载时，用来判断不用下载的记录
            if(record.DownloadStatus == $scope.DownloadStatus.No){
                if(completeFun){
                    completeFun();
                }
                return;
            }
            var serverPath = serverUrl + "/smartplant";

            var focusedRecord= null;    //当前数据库记录
            if($scope.patchLocal != null){
                focusedRecord = $scope.patchLocal;
                $scope.Module.App.FocusedRecord = focusedRecord;
            }

            var isErrDownFile = false,
                isUploadFile = false;   //上传动作是否完成
            if(record.FileName != null && record.FileName != undefined && record.FileName.trim() != ""
                && (focusedRecord == null || record.FileName != focusedRecord.FileName)){
                record.DownloadStatus = $scope.DownloadStatus.Downloading;  //下载中
                //获取上传进度条Element
                var divElement = null;
                if(event.srcElement.innerText == "全部下载"){
                    divElement = scheduleDiv;
                } 
                else{
                    divElement = event.srcElement.parentElement;
                    while(divElement.tagName.toLowerCase() != "div"){
                        divElement = divElement.parentElement;
                    }
                    divElement =  divElement.children[3];
                }

                if(divElement != null){
                    divElement.innerText = "0%";
                    divElement.style.width = "0%";
                    divElement.style.display = '';
                }

                var deleteFileName = null;      //删除文件名
                if(focusedRecord != null){
                    deleteFileName = focusedRecord.FileName;
                }

                var downloadSize = 0;                
                publicSocket.on(record.FileName + "_DownloadSize", function(size) {
                    downloadSize += size;
                    // Circle(downloadSize / record.FileSize);
                    if(divElement != null){
                        divElement.innerText = round.formatPercent(downloadSize / record.FileSize);
                        divElement.style.width = (downloadSize / record.FileSize * 100).toString() + "%";
                    }
                });
                publicSocket.on(record.FileName + "_DownloadComplete", function(IsDownload) {
                    if(IsDownload){
                        //Circle(1);
                        if(divElement != null){
                            divElement.style.width = "100%";
                            divElement.innerText = "100%";
                        }
                    }
                    else{
                        if(divElement != null){
                            divElement.style.width = "0%";
                            divElement.innerText = "";
                        }
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载");
                    }
                    
                    // divElement.style.display = 'none';
                });
                BaseFunction.loading(true);
                BaseService.downloadFile(serverPath, record.FileName, null, deleteFileName, publicSocket.Socket.id, function(data){
                    if(data.Error){
                        isErrDownFile = true;
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    var reqData = {};
                    BaseFunction.httpRequest(serverUrl + "/api/App/saveDownloadTimes", reqData, function(dataTimes){
                        if(dataTimes){
                            isUploadFile = true;
                            updateReord();
                        }
                    },function(errorTimes){
                        BaseFunction.loading(false);
                        BaseFunction.tip("更新下载次数失败", "");
                    });
                    
                });
            }
            else{
                isUploadFile = true;
                if(completeFun){
                    completeFun();
                }
            }

            var updateReord = function(){
                if(isUploadFile){
                    if(!isErrDownFile){
                        if(focusedRecord == null){
                            //新增Record
                            focusedRecord = $scope.Module.App.add();
                            focusedRecord["PreVersion"] = record.Version;
                        }
                        else{
                            focusedRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
                            focusedRecord["PreVersion"] = focusedRecord["Version"];
                        }
                        focusedRecord["AppID"] = record.AppID;
                        focusedRecord["Name"] = record.Name;
                        if(!isErrDownFile ){
                            focusedRecord["Version"] = record.Version;
                        }                        
                        if(!isErrDownFile){
                            focusedRecord["FileName"] = record.FileName;
                            focusedRecord["FileSize"] = record.FileSize;
                        }
                                              
                        focusedRecord["Describe"] = record.Describe;
                        focusedRecord["Remark"] = record.Remark;
                        focusedRecord["IsEffective"] = record.IsEffective;
                        focusedRecord["IsShared"] = record.IsShared;
                        focusedRecord["IsSync"] = false;
                        focusedRecord["Type"] = record.Type;

                        $scope.Module.App.save(function(){
                            if(!isErrDownFile){
                                record["CurrentVersion"] = focusedRecord.Version;
                                record.DownloadStatus = $scope.DownloadStatus.No;
                                record.IsSync = false;
                            }
                            else{
                                record.DownloadStatus = $scope.DownloadStatus.Updatable;
                            }
                            //删除本地补丁，压缩本地补丁，复制，解压缩，删除远程补丁
                            ParameterService.getParameterValue(null,'CopyAddress', function(copyAddress){
                                BaseService.deleteFiles([copyAddress+"/dist.zip"], function(countDist){ 
                                    BaseService.filesZip(copyAddress, copyAddress+"/dist.zip", function(zipData){                          
                                        if(zipData==='close'){
                                            console.log('close');
                                            // BaseService.filesCopy(record.FileName, "//Acer-pc/dc", function(data){
                                            BaseService.filesCopy(record.FileName, copyAddress, function(data){
                                                if(data==='readable copy end'){
                                                    console.log('end');
                                                    // BaseService.filesUnzip("//Acer-pc/dc/"+record.FileName, "//Acer-pc/dc/"+"moduless", function(unzipData){
                                                    BaseService.filesUnzip(copyAddress+"/"+record.FileName, copyAddress, function(unzipData){    
                                                        if(unzipData==='close'){
                                                            console.log('close');
                                                            BaseService.deleteFiles([copyAddress+"/"+record.FileName], function(count){ 
                                                                BaseFunction.loading(false);
                                                            },function(deleteError){
                                                                BaseFunction.loading(false);
                                                            });                   
                                                        }
                                                    },function(unzipError){
                                                        console.log(unzipError);
                                                        BaseFunction.loading(false);
                                                    });
                                                }
                                            },function(error){
                                                console.log(error);
                                                BaseFunction.loading(false);
                                            });
                                        }
                                    },function(zipError){
                                        console.log(zipError);
                                        BaseFunction.loading(false);
                                    });
                                },function(deleteDistError){
                                    BaseFunction.loading(false);
                                }); 
                                
  
                            }); 
                            
                        });
                    }
                }

                if(completeFun){
                    completeFun();
                }
            };
        };  
    
    }
]);
